package inesv.activeMQ.activeMQ_springboot;

import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.messaging.core.MessagePostProcessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.jms.*;
import java.io.Serializable;
import java.util.Queue;

/*
 *消息生产者
 */
@RestController
public class Producer {
    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    ActiveMQQueue test_queue;

    @Autowired
    ActiveMQTopic test_topic;


    @Autowired
    ActiveMQQueue schedule_queue;

    //生产消息
    @RequestMapping("sendQueueMsg")
    public String sendQueueMsg() {
        Email email = new Email();
        email.setFrom("A");
        email.setFrom("B");
        email.setTopic("hello");
        email.setContent("How are you??");
        jmsMessagingTemplate.convertAndSend(test_queue, email);
        return "Queue生产者发生消息：" + email;
    }


    //生产消息
    @RequestMapping("sendTopicMsg")
    public String sendTopicMsg() {
        Email email = new Email();
        email.setFrom("A");
        email.setFrom("B");
        email.setTopic("hello");
        email.setContent("How are you??");
        jmsMessagingTemplate.convertAndSend(test_topic, email);
        return "Topic生产者发生消息：" + email;
    }


    //生产消息
    @RequestMapping("sendScheduleMsg")
    public String sendScheduleMsg() throws JMSException {
        Email email = new Email();
        email.setFrom("A");
        email.setFrom("B");
        email.setTopic("hello");
        email.setContent("How are you??");
        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        ObjectMessage objectMessage = new ActiveMQObjectMessage();
        objectMessage.setObject(email);
        objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 1000 * 10);//延迟10秒发送,时间是毫秒
        MessageProducer producer = session.createProducer(schedule_queue);
        producer.send(objectMessage);
        session.commit();
        producer.close();
        session.close();
        return "Queue生产者发生消息：" + email;
    }


}
